package be.kdg.bombermanunlimited.client.controls;

import java.awt.event.KeyEvent;

import be.kdg.bombermanunlimited.client.Interfaces.ILocalPlayer;

public class KeyList implements java.awt.event.KeyListener {

	long time, updateTime;
	ILocalPlayer player;
	static int timeInterval = 100;
	static int updateTimeInterval= 200;
	boolean isUp, isDown, isLeft, isRight, changed;

	public KeyList(ILocalPlayer player) {
		super();
		isUp = isDown = isLeft = isRight = changed = false;
		this.player = player;
		time = System.currentTimeMillis();
		updateTime= System.currentTimeMillis();
		new Thread(new KeyThread()).start();
	}

	@Override
	public void keyPressed(KeyEvent key) {
		switch (key.getKeyCode()) {
		case KeyEvent.VK_UP:
			isUp= true;
			break;
		case KeyEvent.VK_DOWN:
			isDown= true;
			break;
		case KeyEvent.VK_LEFT:
			isLeft= true;
			break;
		case KeyEvent.VK_RIGHT:
			isRight= true;
			break;
		}
	}

	@Override
	public void keyReleased(KeyEvent key) {
		switch (key.getKeyCode()) {
		case KeyEvent.VK_UP:
			isUp= false;
			break;
		case KeyEvent.VK_DOWN:
			isDown= false;
			break;
		case KeyEvent.VK_LEFT:
			isLeft= false;
			break;
		case KeyEvent.VK_RIGHT:
			isRight= false;
			break;
		}
		// TODO Auto-generated method stub

	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	public class KeyThread implements Runnable {
		@Override
		public void run() {
			while (true) {
			if ((System.currentTimeMillis() - time > timeInterval)) {
				time = System.currentTimeMillis();
				int x  = player.getRow();
				int y = player.getColumn();
				if (isUp) {
					player.incColumn();
				}
				if (isDown) {
					player.decColumn();
				}
				if (isRight) {
					player.incRow();
				}
				if (isLeft) {
					player.decRow();
				}
				int x2= player.getRow();
				int y2= player.getColumn();
				if (x!=x2 | y!=y2) {
					//player.printPosition();
				}
				if (changed== false) {
					changed= isUp || isDown || isRight || isLeft;
				}
					
			}
			try {
				if (System.currentTimeMillis() - time< 20) { 
					Thread.sleep(timeInterval-(System.currentTimeMillis() - time));
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		}
	}

}
